/**
 * 
 */
package com.ydy.task.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.ydy.constant.OrderStatusEnum;
import com.ydy.exception.BusinessException;
import com.ydy.ienum.EnumWechat;
import com.ydy.model.OrderStatus;
import com.ydy.remote.wechat.WeChatApi;
import com.ydy.remote.wechat.exception.WeChatException;
import com.ydy.service.order.OrderService;
import com.ydy.task.TaskService;
import com.ydy.threadpool.TaskPool;
import com.ydy.threadpool.task.OrderCloseTask;
import com.ydy.utils.DateUtil;

/**
 * @author xuzhaojie
 *
 *         2019年3月5日 上午11:25:29
 */
@Service
public class TaskServiceImpl implements TaskService {

	private final static Logger log = LoggerFactory.getLogger(TaskServiceImpl.class);

	private static final ThreadLocal<Integer> THREAD_LOCAL = new ThreadLocal<Integer>();

	private static final Integer RETRY_TIME = 3;
	@Value("${NOT_PAY_TIME_LONG:0d1h0m0s}")
	private String NOT_PAY_TIME_LONG;

	@Autowired
	private OrderService orderService;

	@Scheduled(cron = "${CLOSE_ORDER_TASK:0 * * * * ?}")
	public void orderClose() {
		Long timeLong = DateUtil.formatTimeLong(NOT_PAY_TIME_LONG);
		Date now = new Date();
		Date createTime = new Date(now.getTime() - timeLong);
		log.info("查询订单创建时间小于:" + DateUtil.getDateStrByDateFormat(createTime));
		List<OrderStatus> list = orderService.selectOrderCommit(OrderStatusEnum.COMMIT, createTime);
		if (!CollectionUtils.isEmpty(list)) {
			for (OrderStatus orderStatus : list) {
				TaskPool.execute(new OrderCloseTask(orderStatus.getOrderId(), orderService));
			}
		}
	}

	@Scheduled(cron = "0 0 * * * ?")
	public void requestWechatAccessToken() {
		Integer time = THREAD_LOCAL.get();
		if (time == null) {
			time = RETRY_TIME.intValue();
			THREAD_LOCAL.set(time);
		}
		try {
			if (time < 0) {
				log.error("重复次数用完,获取微信accessToken失败");
				throw new BusinessException(EnumWechat.GET_ACCESS_TOKEN_ERROR);
			}
			time--;
			THREAD_LOCAL.set(time);
			WeChatApi.setAccessToken(WeChatApi.requestAccessToken());
			THREAD_LOCAL.remove();
		} catch (WeChatException e) {
			log.error("获取微信accessToken错误:{}", e.getMessage());
			if (time >= 0) {
				log.info("正在重新获取微信accessToken,第 {} 次", RETRY_TIME - time);
			}
			requestWechatAccessToken();
		}

	}
}
